package com.user.action;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.book.service.IBookService;
import com.booktype.service.IBooktypeService;
import com.common.utils.DigestUtils;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.user.bean.User;
import com.user.service.IUserService;

/**
 * 用户登录动作控制器.
 */
@Controller("loginAction")
@Scope("prototype")
public class LoginAction extends ActionSupport {
	/**
	 * 加载用户登录页面.
 	 * @return 返回SUCCESS, 由Struts加载登录页面
	 */
	public String execute() {
		return SUCCESS;
	}
	
	/**
	 * 处理用户的登录请求.
	 * @return 登录是否成功
	 */
	public String login() {
		if (isUserLegal()) {
			ActionContext.getContext().getSession().put("user", user.getUsername());
			ActionContext.getContext().getSession().put("booktype", booktypeService.getAllBooktype());
			ActionContext.getContext().getSession().put("allbook", bookService.getAllBook());
			return SUCCESS;
        }
		
      return INPUT;
	}
	
	/**
	 * 处理用户的登出请求.
	 * 登出后, 加载用户登录页面.
 	 * 
 	 * @return 返回SUCCESS, 由Struts加载登录页面
	 */
	public String logout() {
		return SUCCESS;
	}
	
	/**
	 * 检查用户合法性.
	 * @return 登录凭证是否合法
	 */
	private boolean isUserLegal() {
		System.out.println("test password: " + user.getPassword());
		String encryptedPassword = DigestUtils.md5Hex(user.getPassword());
		System.out.println("encrypted password: " + encryptedPassword);
		return this.userService.verifyUser(user.getUsername(), encryptedPassword);
	}

	/**
	 * 用于Spring框架注入UserService以实现LoginAction类的功能.
	 * @param userService - 
	 */
	public void setUserService(IUserService userService) {
		this.userService = userService;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	/**
	 * UserService对象, 用于处理User类相关的请求.
	 */
	@Autowired
	private IUserService userService;
	
	@Resource
	private IBooktypeService booktypeService;
	
	@Resource
	private IBookService bookService;
		
	private User user;
	
	/**
	 * 唯一的序列化标识符.
	 */
	private static final long serialVersionUID = -4979316910976237546L;
}
